<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户新增页面</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
</head>
<body>
<form class="layui-form" method="POST" action="" id="layui-form" autocomplete="off">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="username" maxlength="15" lay-verify="required|username" autocomplete="off"
                           placeholder="请输入用户名"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="name" lay-verify="name" maxlength="10" autocomplete="off"
                           placeholder="请输入姓名"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-block">
                    <input type="text" name="email" lay-verify="email" maxlength="18" autocomplete="off"
                           placeholder="请输入邮箱"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item ">
                <label class="layui-form-label">部门</label>
                <div class="layui-input-block">
                    <div id="ID-tree-demo-showCheckbox"></div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">手机</label>
                <div class="layui-input-block">
                    <input type="text" name="phone" lay-verify="phone" autocomplete="off"
                           placeholder="请输入手机号码"
                           class="layui-input" maxlength="11">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="password" name="password" value="" lay-verify="required|password" placeholder="密码"
                           autocomplete="off" maxlength="20" class="layui-input" id="reg-password" lay-affix="eye">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">确认密码</label>
                <div class="layui-input-block">
                    <input type="password" name="confirmPassword" value="" lay-verify="required|confirmPassword"
                           placeholder="确认密码" maxlength="20" autocomplete="off" class="layui-input" lay-affix="eye">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">年龄</label>
                <div class="layui-input-block">
                    <input type="text" name="age" value="" lay-verify="required|age"
                           placeholder="年龄" autocomplete="off" maxlength="3" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-block">
                    <input type="radio" name="sex" value="1" title="男">
                    <input type="radio" name="sex" value="2" title="女">
                </div>
            </div>
            <div class="layui-form-item" id="area-picker">
                <label class="layui-form-label">地址</label>
                <input type="hidden" name="area"/>
                <div class="layui-input-block" style="display: flex; align-items: center; gap: 10px;">
                    <div class="layui-input-inline" style="width: 100px;">
                        <select name="province" class="province-selector" lay-filter="province-1" lay-search>
                            <option value="">请选择省</option>
                        </select>
                    </div>
                    <div class="layui-input-inline" style="width: 100px;">
                        <select name="city" class="city-selector" lay-filter="city-1" lay-search>
                            <option value="">请选择市</option>
                        </select>
                    </div>
                    <div class="layui-input-inline" style="width: 100px;">
                        <select name="county" class="county-selector" lay-filter="county-1" lay-search>
                            <option value="">请选择区</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">头像</label>
                <div class="layui-input-block">
                    <input type="hidden" name="avatar"/>
                    <button type="button" class="layui-btn" id="ID-upload-demo-btn">
                        <i class="layui-icon layui-icon-upload"></i> 上传头像
                    </button>
                    <div style="width: 132px;">
                        <div class="layui-upload-list">
                            <img class="layui-upload-img" id="ID-upload-demo-img" style="width: 100%; height: 92px;"
                                 alt="" src="/work/pear/admin/images/defaultAvatar.jpg">
                            <div id="ID-upload-demo-text"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn  layui-btn-sm" lay-submit=""
                    lay-filter="user-save" id="user-save">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="layui-btn layui-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>
<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/layui/layarea.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:src="@{/pear/js/crypto-js.min.js}"></script>
<script th:src="@{/pear/component/layui/authtree.js}"></script>
<script th:inline="javascript">
    layui.use(['form', 'jquery', 'authtree'], function () {
        let baseURL = /*[[@{/}]]*/ '';
        let form = layui.form;
        let upload = layui.upload;
        let layer = layui.layer;
        let $ = layui.$
        let layarea = layui.layarea;
        let authtree = layui.authtree;
        let parentId = [];
        // 渲染
        $.ajax({
            url: baseURL + "department/list",
            type: 'get',
            success: function (res) {
                let trees = authtree.listConvert(res.data, {
                    primaryKey: 'departmentId'
                    , startPid: 0
                    , parentKey: 'parentId'
                    , nameKey: 'departmentName'
                    , valueKey: 'departmentId'
                    , checkedKey: res.data.departmentId
                });

                authtree.render('#ID-tree-demo-showCheckbox', trees, {
                    autoWidth: true,
                    openChecked: true,
                    autochecked: false,
                    autoclose: false
                });
                authtree.on('change(#ID-tree-demo-showCheckbox)', function () {
                    // 获取选中节点
                    parentId = authtree.getChecked('#ID-tree-demo-showCheckbox');
                });

            }
        })
        layarea.render({
            elem: '#area-picker',
            change: function (res) {
                $("[name=area]").val(res.province + res.city + res.county);
            }
        });
        // 自定义验证规则
        form.verify({
            // 验证用户名，且为必填项
            username: function (value) {
                // 正则表达式，只允许字母、数字和下划线，且不能以下划线开始
                if (!new RegExp("^[a-zA-Z0-9][a-zA-Z0-9_]*$").test(value)) {
                    return '请输入有效的用户名';
                }
            },
            age: function (value) {
                if (!/^\d+$/.test(value)) {
                    return '年龄必须是有效数字';
                }
                if (value < 1 || value > 150) {
                    return '年龄必须在1到150之间';
                }
            },
            password: function (value) {
                if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[~!@&%#_])[a-zA-Z0-9~!@&%#_]{8,20}$/.test(value)) {
                    return '密码必须包含数字、大小写字母和特殊字符，长度8到20位';
                }
            },
            confirmPassword: function (value) {
                let passwordValue = $('#reg-password').val();
                if (value !== passwordValue) {
                    return '两次密码输入不一致';
                }
            }

        });
        let avatarSize;
        $.ajax({
            url: baseURL + "setting/getSettingValue",
            type: 'get',
            data: {
                settingKey: "AVATAR_SIZE"
            },
            success: function (res) {
                avatarSize = parseInt(res.data, 10)
            }
        })
        upload.render({
            elem: '#ID-upload-demo-btn',
            url: baseURL + 'user/uploadAvatar',
            size: avatarSize,   //默认单位为kb
            before: function (obj) {
                // 预读本地文件示例，不支持ie8
                layer.msg('上传中', {icon: 16, time: 0});
            },
            done: function (res) {
                $('#ID-upload-demo-img').attr('src', baseURL + res.data);
                $("[name=avatar]").val(res.data);
                if (res.code === 1000) {
                    return layer.msg('上传成功');
                } else {
                    return layer.msg(res.msg, {icon: 2, time: 2000});
                }
            }
        });

        $(document).ready(function () {
            // 监听表单提交
            form.on('submit(user-save)', function (data) {

                // 获取提交按钮
                let submitButton = $('#user-save');
                // 禁用按钮，防止重复提交
                submitButton.addClass('layui-btn-disabled').attr('disabled', 'disabled');
                // 使用AES加密密码
                let key = CryptoJS.enc.Utf8.parse('3f5279c6d4a12f58'); // 密钥应该是一个保密的字符串
                let iv = CryptoJS.enc.Utf8.parse('d4e2f6a0b8c0d2e8'); // 初始化向量，可以是任意值，但解密时需要相同
                let encryptedPassword = CryptoJS.AES.encrypt(data.field.password, key, {
                    iv: iv,
                    mode: CryptoJS.mode.CBC,
                    padding: CryptoJS.pad.Pkcs7
                });
                data.field.password = encryptedPassword.toString();
                data.field.departmentIds = parentId
                console.log(data.field);
                // 发送 AJAX 请求
                $.ajax({
                    url: baseURL + 'user/add',
                    type: 'post',
                    data: JSON.stringify(data.field),
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function (result) {
                        if (result.code === 1000) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 2000
                            }, function () {
                                parent.layer.close(parent.layer.getFrameIndex(window.name)); // 关闭当前页
                                parent.layui.table.reload("user-table"); // 重新加载表格
                            });
                        } else {
                            layer.msg(result.msg, {
                                icon: 2,
                                time: 2000
                            });
                        }
                        // 5秒后重新启用按钮
                        setTimeout(function () {
                            submitButton.removeClass('layui-btn-disabled').removeAttr('disabled');
                        }, 5000);
                    },
                    error: function (xhr, status, error) {
                        console.error("Error occurred: " + error);
                        // 可以在这里添加错误处理逻辑
                    }
                });
                return false; // 阻止表单的默认提交行为
            });
        });
    })
</script>
</body>
</html>
